package com.poly.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poly.common.core.constant.DictConstants;
import com.poly.common.core.domain.R;
import com.poly.common.core.tools.utils.Func;
import com.poly.common.core.tools.utils.StringUtil;
import com.poly.common.core.utils.AssertUtil;
import com.poly.common.core.utils.ConvertUtils;
import com.poly.common.core.web.page.Pagination;
import com.poly.common.security.utils.DictUtils;
import com.poly.system.domain.SysClientVersion;
import com.poly.system.mapper.SysClientVersionMapper;
import com.poly.system.pojo.dto.SysClientVersionDTO;
import com.poly.system.pojo.query.SysClientVersionQuery;
import com.poly.system.pojo.vo.SysClientVersionVO;
import com.poly.system.service.ISysClientVersionService;
import com.poly.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户端版本Service业务层处理
 *
 * @author poly
 * @date 2023-09-26
 */
@Slf4j
@Service
public class SysClientVersionServiceImpl extends ServiceImpl<SysClientVersionMapper, SysClientVersion> implements ISysClientVersionService {

    @Autowired
    private ISysUserService userService;

    /**
     * 获取查询对象
     *
     * @param query
     * @return
     */
    public LambdaQueryWrapper<SysClientVersion> getWrapper(SysClientVersionQuery query) {
        LambdaQueryWrapper<SysClientVersion> wrapper = null;
        if (Func.isNotEmpty(query)) {
            wrapper = Wrappers.<SysClientVersion>lambdaQuery();
            wrapper.eq(Func.isNotEmpty(query.getId()), SysClientVersion::getId, query.getId());
            wrapper.eq(Func.isNotEmpty(query.getClientType()), SysClientVersion::getClientType, query.getClientType());
            wrapper.like(Func.isNotEmpty(query.getClientName()), SysClientVersion::getClientName, query.getClientName());
            wrapper.eq(Func.isNotEmpty(query.getVersion()), SysClientVersion::getVersion, query.getVersion());
            wrapper.eq(Func.isNotEmpty(query.getVersionNum()), SysClientVersion::getVersionNum, query.getVersionNum());
            wrapper.eq(Func.isNotEmpty(query.getFlag()), SysClientVersion::getFlag, query.getFlag());
            wrapper.eq(Func.isNotEmpty(query.getSuffix()), SysClientVersion::getSuffix, query.getSuffix());
            wrapper.eq(Func.isNotEmpty(query.getCoerce()), SysClientVersion::getCoerce, query.getCoerce());
            wrapper.eq(Func.isNotEmpty(query.getStatus()), SysClientVersion::getStatus, query.getStatus());
        }
        return wrapper;
    }

    /**
     * 查询客户端版本
     *
     * @param id 客户端版本主键
     * @return 客户端版本
     */
    @Override
    public SysClientVersion get(Long id) {
        return getById(id);
    }


    /**
     * 查询客户端版本
     *
     * @param id 客户端版本主键
     * @return 客户端版本
     */
    @Override
    public SysClientVersionVO getVO(Long id) {
        return null;
    }

    @Override
    public List<SysClientVersionVO> getVO(List<SysClientVersionVO> list) {
        if (Func.isNotEmpty(list)) {
            Map<Long, String> userNameMap = userService.getUserNameMap(list.stream().map(SysClientVersionVO::getCreateBy).distinct().collect(Collectors.toList()));
            list.forEach(p -> {
                if (Func.isNotEmpty(userNameMap)) {
                    p.setCreateByDesc(userNameMap.get(p.getCreateBy()));
                }
                p.setStatusDesc(DictUtils.getDictLabel(DictConstants.COMMON_STATUS, p.getStatus()));
                p.setCoerceDesc(DictUtils.getDictLabel(DictConstants.IS, p.getCoerce()));
            });
        }
        return list;
    }

    /**
     * 查询客户端版本分页
     *
     * @param query 客户端版本
     * @return 客户端版本
     */
    public Pagination<SysClientVersionVO> queryPage(SysClientVersionQuery query) {
        IPage<SysClientVersion> page = baseMapper.selectPage(
                query.getPage(),
                getWrapper(query)
        );
        Pagination<SysClientVersionVO> pagination = Pagination.toPagination(page, SysClientVersionVO.class);
        getVO(pagination.getRows());
        return pagination;
    }

    /**
     * 查询客户端版本列表
     *
     * @param query 客户端版本
     * @return 客户端版本
     */
    @Override
    public List<SysClientVersionVO> list(SysClientVersionQuery query) {
        List<SysClientVersionVO> list = ConvertUtils.convert(list(getWrapper(query)), SysClientVersionVO.class);
        getVO(list);
        return list;
    }

    /**
     * 新增客户端版本
     *
     * @param dto 客户端版本
     * @return 结果
     */
    @Override
    public R add(SysClientVersionDTO dto) {
        int versionNum = ConvertUtils.toInteger(dto.getVersion().replaceAll("\\.", ""), 0);
        if (versionNum == 0) {
            return R.fail("版本号不正确：" + dto.getVersion());
        }
        long count = count(Wrappers.<SysClientVersion>lambdaQuery().eq(SysClientVersion::getVersion, dto.getVersion()));
        if (count == 0) {
            String url = dto.getUrl();
            SysClientVersion model = ConvertUtils.convert(dto, SysClientVersion.class);
            model.setVersionNum(versionNum);
            if (url.indexOf(".") > -1) {
                model.setSuffix(url.substring(url.lastIndexOf(".")));
            }
            save(model);
            return R.ok(model.getId());
        }
        return R.fail("版本号已经存在：" + dto.getVersion());
    }

    /**
     * 修改客户端版本
     *
     * @param dto 客户端版本
     * @return 结果
     */
    @Override
    public R update(SysClientVersionDTO dto) {
        int versionNum = ConvertUtils.toInteger(dto.getVersion().replaceAll("\\.", ""), 0);
        if (versionNum == 0) {
            return R.fail("版本号不正确：" + dto.getVersion());
        }
        SysClientVersion model = getOne(Wrappers.<SysClientVersion>lambdaQuery().eq(SysClientVersion::getVersion, dto.getVersion()), false);
        if (model == null || dto.getId().equals(model.getId())) {
            if (model == null) {
                model = get(dto.getId());
            }
            if (null != model) {
                String url = dto.getUrl();
                model.setVersionNum(versionNum);
                model.setClientType(dto.getClientType());
                model.setVersion(dto.getVersion());
                model.setClientName(dto.getClientName());
                model.setFlag(dto.getFlag());
                model.setUrl(dto.getUrl());
                if (url.indexOf(".") > -1) {
                    model.setSuffix(url.substring(url.lastIndexOf(".")));
                }
                model.setCoerce(dto.getCoerce());
                model.setStatus(dto.getStatus());
                model.setRemarks(dto.getRemarks());
                updateById(model);
                return R.ok(model.getId());
            }
            return R.fail("APP版本管理: " + model.getId() + ",不存在！");
        }
        return R.fail("版本号已经存在：" + model.getVersion());
    }

    /**
     * 批量删除客户端版本
     *
     * @param ids 需要删除的客户端版本主键
     * @return 结果
     */
    @Override
    public boolean deleteByIds(Long[] ids) {
        return removeBatchByIds(Arrays.asList(ids));
    }

    /**
     * 删除客户端版本信息
     *
     * @param id 客户端版本主键
     * @return 结果
     */
    @Override
    public boolean deleteById(Long id) {
        return removeById(id);
    }

    @Override
    public SysClientVersionVO checkNewest(SysClientVersionQuery query) {
        AssertUtil.isFalse(null == query.getVersionNum() || StringUtil.isBlank(query.getFlag()), "非法参数！");
        log.info("SysClientVersionServiceImpl->checkNewest()\tclientType:{},versionNum:{},flag:{}", query.getClientType(), query.getVersionNum(), query.getFlag());
        SysClientVersion model = getOne(Wrappers.<SysClientVersion>lambdaQuery()
                .eq(SysClientVersion::getClientType, query.getClientType())
                .eq(SysClientVersion::getStatus, 0)
                .gt(SysClientVersion::getVersionNum, query.getVersionNum())
                .eq(SysClientVersion::getFlag, query.getFlag()), false);
        log.info("SysAppVersionService->checkNewest()-return:" + JSON.toJSONString(model));
        return ConvertUtils.convert(model, SysClientVersionVO.class);
    }

    @Override
    public SysClientVersionVO getVersionInfo(SysClientVersionQuery query) {
        AssertUtil.isFalse(null == query.getVersionNum() || StringUtil.isBlank(query.getFlag()), "非法参数！");
        log.info("SysClientVersionServiceImpl->checkNewest()\tclientType:{},versionNum:{},flag:{}", query.getClientType(), query.getVersionNum(), query.getFlag());
        SysClientVersion model = getOne(Wrappers.<SysClientVersion>lambdaQuery()
                .eq(SysClientVersion::getClientType, query.getClientType())
                .eq(SysClientVersion::getStatus, 0)
                .eq(SysClientVersion::getVersionNum, query.getVersionNum())
                .eq(SysClientVersion::getFlag, query.getFlag()), false);
        log.info("SysAppVersionService->checkNewest()-return:" + JSON.toJSONString(model));
        return ConvertUtils.convert(model, SysClientVersionVO.class);
    }
}
